import { defineStore } from "pinia";
export const imStore = defineStore("imStore", {
  unistorage: false, // 是否持久化
  state: () => {
    return {
		isLogin: false,
		conversationList: [] as any,
		messageList: [] as any,
		isCompleted: true,
		conversationSearch:"",
		conversation: {} as any,
		conversationID: "",
		scrollTop: 0,
		groupList:[] as any,
		friendshipData:{
		unreadCount:0,
		friendApplicationList:[] as any,
		},
		friends:[] as any,
		groupApplicationList:[] as any,
		groupApplicationListRead:[] as any,
		groupDetail:{} as any, //后端数据
		groupProfile:{} as any,
		groupMembers:[] as any,
		revokedMsg:[] as any,
		vipMap:{} as any,
		isReconnection:false,
		isReset:true,
		currentMessage:0,//当前消息条数
		receiving:false,//消息接收中
    };
  },
  getters: {
    totalUnread: (state) => {
        let total = 0;
        state.conversationList.forEach((c:any)=>{
            if(c.conversationID !== "@TIM#SYSTEM"&&c.messageRemindType!=="AcceptNotNotify"){
                total+=Number(c.unreadCount);
            }
        })



        return total;
    },
    quanziTotalUnread: (state) => {
        let total = 0;
        state.conversationList.forEach((c:any)=>{
            if(c.conversationID !== "@TIM#SYSTEM"&&c.messageRemindType!=="AcceptNotNotify"){
                total+=Number(c.unreadCount);
            }
        })

        total+=state.friendshipData.unreadCount;

        total+=state.groupApplicationList.length-state.groupApplicationListRead.length;

        /*#ifdef APP-PLUS*/
        //plus.runtime.setBadgeNumber(total);
        /*#endif*/


        return total;
    },
    tongxunluUnread: (state) => {
        let total = 0;

        total+=state.friendshipData.unreadCount;

        total+=state.groupApplicationList.length-state.groupApplicationListRead.length;

        return total;
    },
  },
  actions: {
    setscrollTop(payload: number): void {
      this.scrollTop = payload;
    },

    setFriends(payload: any): void {
        payload.forEach((friend:any) => {
            this.conversationList.forEach((conversation:any) => {
                if(conversation.type==="C2C"&&conversation.userProfile.userID===friend.userID){
                    conversation.userProfile = friend.profile
                }
            })
        })


        this.friends = payload.filter((item:any)=>item.userID!=='adminkefu');
    },
    setGroupList(payload: any): void {
        this.groupList = payload;
    },
    delGroup(groupId:string):void {
        this.groupList = this.groupList.filter((item:any)=>item.groupID!==groupId);
        setTimeout(()=>{
            uni.$emit("groupListUpdate");
        },0)
    },

    updateGroupListByIndex(payload: any): void {
        this.groupList[payload.index] = payload.value;
    },

    setConversationList(payload: any): void {
      this.conversationList = payload;
    },

    updateRevoke(payload: any): void {

        if(!Array.isArray(payload)){
            return
        }

        if(!payload.length){
            return;
        }

        if(this.messageList.length){
            this.messageList = this.messageList.map(((item:any)=>{
                payload.forEach((revokeItem:any)=>{
                    if(item.ID===revokeItem.ID){
                        item.isRevoked = true;
                    }
                })
                return item;
            }))
        }

        if(this.conversationList.length){
            this.conversationList = this.conversationList.map(((item:any)=>{
                payload.forEach((revokeItem:any)=>{
                    if(item.conversationID===revokeItem.conversationID){
                       if(item.lastMessage.ID===revokeItem.ID){
                           item.lastMessage = {
                            ...item.lastMessage,
                            ...revokeItem
                           }
                       }
                    }
                })
                return item;
            }))

        }



    },

    updateConversationListGroupProfile(payload: any): void {
        this.conversationList.forEach((conversation:any,index:number)=>{
            if(conversation.conversationID === `GROUP${payload.value.groupID}`){
                this.conversationList[index].groupProfile = payload.value;
            }
        })
    },


    updateConversationGroupProfile(payload: any): void {
        this.conversation.groupProfile = payload;
    },

    setConversation(payload: object): void {
      this.conversation = payload;
    },
    setConversationSearch(payload: string): void {
      this.conversationSearch = payload;
    },
    setConversationID(payload: string): void {
      this.conversationID = payload;
    },
    resetConversationID(): void {
      this.conversationID = "";
    },
    setMessageList( payload: any): void {
      this.messageList = payload;
    },
    unshiftMessageList( payload: any): void {
      this.messageList.unshift(payload);
    },
    pushMessageList( payload: any): void {
      this.messageList.push(payload);
    },
    // updateLastMessage(message:any): void {
    //   this.messageList.forEach((item=>{
    //     if(item.ID===message.ID){
    //         item  = message;
    //     }
    //   }))
    // },
    clearMessageList(): void {
		this.messageList = []
      //this.messageList.length = 0;
    },
    setFriendshipData( payload: any): void {
      this.friendshipData = payload;
    },
    setGroupApplicationList( payload: any): void {
      this.groupApplicationList = payload;
    },
    setGroupRead(): void {
        const arr:any = [];
        this.groupApplicationList.forEach((item:any) =>{
            if(this.groupApplicationListRead.every((readedItem:any)=>readedItem.time!==item.time)){
                arr.push(item);
            }
        })

        this.groupApplicationListRead=[...this.groupApplicationListRead,...arr];

    },
    syncGroupRead(): void {
        const arr:any = [];
        this.groupApplicationListRead.forEach((readedItem:any,index:number) =>{
            if(this.groupApplicationList.every((item:any)=>item.time!==readedItem.time)){
                arr.push(readedItem);
            }
        })

        arr.forEach((item:any)=>{
            this.groupApplicationListRead.forEach((readedItem:any,index:number)=>{
                if(readedItem.time===item.time){
                    this.groupApplicationListRead.splice(index,1);
                }
            })
        })
    },
    setGroupDetail(payload:any){
        this.groupDetail = payload;
    },
    setGroupProfile(payload:any){
        this.groupProfile = payload;
    },
    pushGroupMembers(payload:any){
		this.groupMembers = [...payload];
        //console.log("设置的群成员个数",this.groupMembers.length)
        //this.groupMembers = [...this.groupMembers,...payload];
    },
    clearGroupMembers(){
        this.groupMembers = [];
    },
    resetChat(): void {
      this.messageList = [];
      this.isCompleted = true;
    },
    setVipMap(payload:any): void {
        this.vipMap = payload;
    },
    setIsCompleted(payload:boolean): void {
        this.isCompleted = payload;
    },
	setReconnection(is:boolean):void{
		this.isReconnection = is
	},
	setReset(is:boolean):void{
		this.isReset = is
	},
	plusMessageQuantity():void{
		this.currentMessage ++
	},
	clearMessageQuantity():void{
		this.currentMessage = 0
	},
	setReceiving(is:boolean):void{
		this.receiving = is
	},
	clearImData(){
	    this.isLogin = false,
	    this.conversationList = []
	    this.messageList = []
	    this.isCompleted = true,
	    this.conversationSearch = ""
	    this.conversation = {}
	    this.conversationID =  ""
	    this.scrollTop = 0
	    this.groupList = []
	    this.friendshipData = {}
	    this.friends = [] 
	    this.groupApplicationList = []
	    this.groupApplicationListRead = []
	    this.groupDetail = {}
	    this.groupProfile = {}
	    this.groupMembers = []
	    this.revokedMsg = []
	    this.vipMap = {}
	    this.isReconnection = false
	    this.isReset = true
		this.currentMessage = 0
		this.receiving = false
	}
	},
	
});

// export default defineStore('userData', {
//     unistorage: true,
//     state: () => ({ id: '123456',accessToken: null}),
//     // getters: {
//     //   double: (state) => state.count * 2,
//     // },
//     actions: {
//       setUserData({id,accessToken}:any) {
//         this.id = id;
//         this.id = accessToken;
//       },
//     },
//   })

//   export const userData = defineStore('counter', () => {
//     const id = ref(11111111)
//     function setUserData() {
//       id.value = 44444444
//     }

//     return { id, setUserData }
//   })
